package com.relytosoft.mizar.media.common.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.relytosoft.dubhe.common.core.exception.ServiceException;
import com.relytosoft.dubhe.common.core.object.ResponseResult;
import com.relytosoft.dubhe.common.redis.utils.RedisUtil;
import com.relytosoft.mizar.media.common.config.OpenApiProperty;
import com.relytosoft.mizar.media.common.constant.MediaCommonConstants;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 海康OpenApi的Token获取工具类
 *
 * @author Jierry
 * @version 2022/4/6.
 */

public class HkRequestUtil {

    /**
     * 获得海康的访问Token
     *
     * @return {@link String}
     * @see String
     */
    public static String getToken() {

        Object token = RedisUtil.get(MediaCommonConstants.CACHE_HKTOKENNAME);
        if (ObjectUtil.isNotEmpty(token)) {
            return token.toString();
        }

        // 平台的ip端口
        ArtemisConfig.host = OpenApiProperty.openApiUrls;
        // 密钥appkey
        ArtemisConfig.appKey = OpenApiProperty.appkeys;
        // 密钥appSecret
        ArtemisConfig.appSecret = OpenApiProperty.appSecrets;
        //ArtemisConfig.host = "192.168.100.171:443"; // 平台的ip端口
        //ArtemisConfig.appKey = "29603581";  // 密钥appkey
        //ArtemisConfig.appSecret = "z8LHRpB77i1ARlshKhTb";// 密钥appSecret

        final String ARTEMIS_PATH = "/artemis";
        final String previewURLsApi = ARTEMIS_PATH + "/api/v1/oauth/token";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", previewURLsApi);//根据现场环境部署确认是http还是https
            }
        };

        /**
         * STEP4：设置参数提交方式
         */
        String contentType = "application/json";

        /**
         * STEP5：组装请求参数
         */
//        JSONObject jsonBody = new JSONObject();
//        jsonBody.put("cameraIndexCode", "748d84750e3a4a5bbad3cd4af9ed5101");
//        jsonBody.put("streamType", 0);
//        jsonBody.put("protocol", "rtsp");
//        jsonBody.put("transmode", 1);
//        jsonBody.put("expand", "streamform=ps");
//        String body = jsonBody.toJSONString();
        /**
         * STEP6：调用接口
         */
        String result = ArtemisHttpUtil.doPostStringArtemis(path, "", null, null, contentType, null);// post请求application/json类型参数
        JSONObject jsonObject = JSON.parseObject(result);
        JSONObject jsonObject2 = JSON.parseObject(jsonObject.getString("data"));
        String tokenStr = jsonObject2.getString("access_token");
        RedisUtil.set(MediaCommonConstants.CACHE_HKTOKENNAME, tokenStr, 36000L);
        return tokenStr;
    }

    public static MultiValueMap<String, String> createJsonRequestHeader() {
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("access_token", HkRequestUtil.getToken());
        headers.add("Content-Type", MediaCommonConstants.JSON_HEADER);
        return headers;
    }

    public static String handlerResponse(String result) {
        if (StrUtil.isEmpty(result)) {
            throw new ServiceException("HK接口返回的结果错误");
        }
        try {
            ResponseResult responseResult = JSON.parseObject(result, ResponseResult.class);
            if (responseResult.getCode() != 0) {
                throw new ServiceException("HK接口返回的结果错误:" + responseResult.getMsg());
            }
            Object data = responseResult.getData();
            return Objects.isNull(data) ? null : data.toString();
        } catch (Exception ex) {
            throw new ServiceException(ex.getMessage());
        }
    }
}
